function _typeof(obj) {
  '@babel/helpers - typeof';
  return (
    (_typeof =
      'function' == typeof Symbol && 'symbol' == typeof Symbol.iterator
        ? function (obj) {
            return typeof obj;
          }
        : function (obj) {
            return obj &&
              'function' == typeof Symbol &&
              obj.constructor === Symbol &&
              obj !== Symbol.prototype
              ? 'symbol'
              : typeof obj;
          }),
    _typeof(obj)
  );
}
var _excluded = ['value', 'onChange', 'onPanelChange', 'scheduledDates', 'headerRender'];
function _extends() {
  _extends = Object.assign
    ? Object.assign.bind()
    : function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];
          for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }
        return target;
      };
  return _extends.apply(this, arguments);
}
function _defineProperty(obj, key, value) {
  key = _toPropertyKey(key);
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true,
    });
  } else {
    obj[key] = value;
  }
  return obj;
}
function _toPropertyKey(arg) {
  var key = _toPrimitive(arg, 'string');
  return _typeof(key) === 'symbol' ? key : String(key);
}
function _toPrimitive(input, hint) {
  if (_typeof(input) !== 'object' || input === null) return input;
  var prim = input[Symbol.toPrimitive];
  if (prim !== undefined) {
    var res = prim.call(input, hint || 'default');
    if (_typeof(res) !== 'object') return res;
    throw new TypeError('@@toPrimitive must return a primitive value.');
  }
  return (hint === 'string' ? String : Number)(input);
}
function _slicedToArray(arr, i) {
  return (
    _arrayWithHoles(arr) ||
    _iterableToArrayLimit(arr, i) ||
    _unsupportedIterableToArray(arr, i) ||
    _nonIterableRest()
  );
}
function _nonIterableRest() {
  throw new TypeError(
    'Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.',
  );
}
function _unsupportedIterableToArray(o, minLen) {
  if (!o) return;
  if (typeof o === 'string') return _arrayLikeToArray(o, minLen);
  var n = Object.prototype.toString.call(o).slice(8, -1);
  if (n === 'Object' && o.constructor) n = o.constructor.name;
  if (n === 'Map' || n === 'Set') return Array.from(o);
  if (n === 'Arguments' || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))
    return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  return arr2;
}
function _iterableToArrayLimit(arr, i) {
  var _i =
    null == arr
      ? null
      : ('undefined' != typeof Symbol && arr[Symbol.iterator]) || arr['@@iterator'];
  if (null != _i) {
    var _s,
      _e,
      _x,
      _r,
      _arr = [],
      _n = !0,
      _d = !1;
    try {
      if (((_x = (_i = _i.call(arr)).next), 0 === i)) {
        if (Object(_i) !== _i) return;
        _n = !1;
      } else
        for (
          ;
          !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i);
          _n = !0
        );
    } catch (err) {
      (_d = !0), (_e = err);
    } finally {
      try {
        if (!_n && null != _i.return && ((_r = _i.return()), Object(_r) !== _r)) return;
      } finally {
        if (_d) throw _e;
      }
    }
    return _arr;
  }
}
function _arrayWithHoles(arr) {
  if (Array.isArray(arr)) return arr;
}
function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  var target = _objectWithoutPropertiesLoose(source, excluded);
  var key, i;
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
      target[key] = source[key];
    }
  }
  return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;
  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }
  return target;
}
import LeftOutlined from '@ant-design/icons/LeftOutlined';
import RightOutlined from '@ant-design/icons/RightOutlined';
import { useMount } from '@szzj/hooks';
import { Calendar } from 'antd';
import classnames from 'classnames';
import dayjs from 'dayjs';
import localeData from 'dayjs/plugin/localeData';
import weekday from 'dayjs/plugin/weekday';
import React, { useCallback, useEffect, useState } from 'react';
import createField from '../../createField';
import './index.less';
var CLS_PREFIX = 'szzj-calendar-panel';
dayjs.extend(weekday);
dayjs.locale('zh-cn');
dayjs.extend(localeData);

/**
 * 日历
 * @returns
 */
function CalendarPanel(_ref) {
  var value = _ref.value,
    onChange = _ref.onChange,
    onPanelChange = _ref.onPanelChange,
    scheduledDates = _ref.scheduledDates,
    headerRender = _ref.headerRender,
    rest = _objectWithoutProperties(_ref, _excluded);
  var _useState = useState(value !== null && value !== void 0 ? value : dayjs()),
    _useState2 = _slicedToArray(_useState, 2),
    innerValue = _useState2[0],
    setInnerValue = _useState2[1];
  useEffect(
    function () {
      var dateFromValue = value !== null && value !== void 0 ? value : dayjs();
      if (
        !(innerValue !== null && innerValue !== void 0 && innerValue.isSame(dateFromValue, 'day'))
      )
        setInnerValue(value);
    },
    [value],
  );

  /** 计算起始、结束日期 */
  var getDateRange = useCallback(function (date) {
    var weekday = date.weekday();
    var monthStartDate = date.date(1);
    var startDate =
      monthStartDate === null || monthStartDate === void 0
        ? void 0
        : monthStartDate.add(-weekday, 'day');
    if (startDate.month() === date.month() && startDate.day() !== 1) {
      var _startDate;
      startDate =
        (_startDate = startDate) === null || _startDate === void 0
          ? void 0
          : _startDate.add(-7, 'day');
    }
    var endDate =
      monthStartDate === null || monthStartDate === void 0
        ? void 0
        : monthStartDate.add(-weekday + 41, 'day');
    return [startDate, endDate];
  }, []);
  useMount(function () {
    if (innerValue) {
      var _getDateRange = getDateRange(innerValue),
        _getDateRange2 = _slicedToArray(_getDateRange, 2),
        _startDate2 = _getDateRange2[0],
        _endDate = _getDateRange2[1];
      onPanelChange === null || onPanelChange === void 0
        ? void 0
        : onPanelChange(_startDate2, _endDate);
      onChange === null || onChange === void 0 ? void 0 : onChange(innerValue);
    }
  });

  /** 变更选中日期 */
  var triggerDateChange = useCallback(
    function (date) {
      setInnerValue(date);
      onChange === null || onChange === void 0 ? void 0 : onChange(date);
    },
    [onChange],
  );

  /** 变更月份 */
  var triggerMonthChange = useCallback(
    function (month) {
      var date =
        innerValue === null || innerValue === void 0
          ? void 0
          : innerValue.clone().year(month.year()).month(month.month());
      if (date) {
        triggerDateChange(date);
        var _getDateRange3 = getDateRange(date),
          _getDateRange4 = _slicedToArray(_getDateRange3, 2),
          _startDate3 = _getDateRange4[0],
          _endDate2 = _getDateRange4[1];
        onPanelChange === null || onPanelChange === void 0
          ? void 0
          : onPanelChange(_startDate3, _endDate2);
      }
    },
    [onPanelChange, triggerDateChange, getDateRange],
  );

  /** 定制头部 */
  var innerHeaderRender = useCallback(
    function (_ref2) {
      var value = _ref2.value;
      var createMonthChanger = function createMonthChanger(offset) {
        return function () {
          var month = value.clone().month(value.month() + offset);
          triggerMonthChange(month);
        };
      };
      return /*#__PURE__*/ React.createElement(
        'div',
        {
          className: ''.concat(CLS_PREFIX, '-header'),
        },
        /*#__PURE__*/ React.createElement('div', null, value.format('YYYY年M月')),
        /*#__PURE__*/ React.createElement(
          'div',
          null,
          /*#__PURE__*/ React.createElement(LeftOutlined, {
            style: {
              marginRight: '20px',
            },
            onClick: createMonthChanger(-1),
          }),
          /*#__PURE__*/ React.createElement(RightOutlined, {
            onClick: createMonthChanger(+1),
          }),
        ),
      );
    },
    [triggerMonthChange],
  );
  var finalHeaderRender = headerRender || innerHeaderRender;

  /** 定制日期单元 */
  var fullCellRender = useCallback(
    function (date) {
      var _classnames;
      var isToday = date === null || date === void 0 ? void 0 : date.isSame(dayjs(), 'day');
      var isAvtived = date === null || date === void 0 ? void 0 : date.isSame(innerValue, 'day');
      var isScheduled =
        scheduledDates === null || scheduledDates === void 0
          ? void 0
          : scheduledDates.some(function (it) {
              return it.isSame(date, 'day');
            });
      var cellClsPrefix = ''.concat(CLS_PREFIX, '-date-cell');
      var cellCalssName = classnames(
        ((_classnames = {}),
        _defineProperty(_classnames, cellClsPrefix, true),
        _defineProperty(_classnames, ''.concat(cellClsPrefix, '-actived'), isAvtived),
        _classnames),
      );
      return /*#__PURE__*/ React.createElement(
        'div',
        {
          className: ''.concat(cellClsPrefix, '-wrapper'),
        },
        /*#__PURE__*/ React.createElement(
          'div',
          {
            className: cellCalssName,
          },
          isToday ? '今' : date.format('D'),
        ),
        isScheduled &&
          /*#__PURE__*/ React.createElement('i', {
            className: ''.concat(cellClsPrefix, '-scheduled'),
          }),
      );
    },
    [innerValue, scheduledDates],
  );
  return /*#__PURE__*/ React.createElement(
    Calendar,
    _extends(
      {
        className: CLS_PREFIX,
        fullscreen: false,
      },
      rest,
      {
        // @ts-ignore
        value: value,
        // @ts-ignore
        onSelect: triggerDateChange,
        // @ts-ignore
        onPanelChange: triggerMonthChange,
        // @ts-ignore
        headerRender: finalHeaderRender,
        // antd4版本属性，在5版本改为fullCellRender
        // @ts-ignore
        dateFullCellRender: fullCellRender,
        fullCellRender: fullCellRender,
      },
    ),
  );
}
export default createField(CalendarPanel, {
  defaultDetailComponent: function defaultDetailComponent(_ref3) {
    var value = _ref3.value;
    return /*#__PURE__*/ React.createElement(Calendar, {
      className: CLS_PREFIX,
      fullscreen: false,
      value: value,
      onSelect: function onSelect() {},
      onChange: function onChange() {},
      onPanelChange: function onPanelChange() {},
      headerRender: function headerRender() {
        return /*#__PURE__*/ React.createElement('div', null, value.format('YYYY/MM/DD'));
      },
    });
  },
});
